package article

import (
	"fmt"
	"gin_blog/model"
	"github.com/gin-gonic/gin"
	"net/http"
)

/*
	获取文章详情
	url:/api/v1/articles/:article_id
	method: get111
*/
func articleGet(ctx *gin.Context) {
	//获取数据库对象
	db := model.GetDB()
	defer db.Close()
	//获取数据库对象
	var BlogModel model.BlogModel
	//获取文章的id
	articleID := ctx.Param("article_id")
	fmt.Println(articleID)
	//根据文章id去查询
	db.First(&BlogModel, "id=? and is_delete=?", articleID,0) //指定根据name去查询用户的id
	//返回应答
	ctx.JSON(http.StatusOK, map[string]interface{}{
		"code": 200,
		"msg":  "ok",
		"data": BlogModel,
	})
}


/*
	新增文件
	url:/api/v1/articles
	method: post
*/
func articlePost(ctx *gin.Context) {
	//获取数据库对象
	db := model.GetDB()
	defer db.Close()

	//绑定结构体
	var airticle ModelArticle //表单绑定对象
	var tokenModel model.UserTokenModel

	//参数验证
	err := ctx.ShouldBind(&airticle)
	if err != nil {
		ctx.JSON(http.StatusNotFound, map[string]interface{}{
			"code": 4001,
			"msg":  "数据绑定失败",
			"data": "",
		})
		return
	}
	//获取用户信息
	token := ctx.Query("token")
	fmt.Println("token:", token)

	//根据用户查userid
	db.First(&tokenModel, "token=?", token) //指定根据name去查询用户的id
	fmt.Println("tokenModel.UserId", tokenModel.UserId)
	fmt.Println("tokenModel.Token", tokenModel.Token)

	// 获取用户的id
	db.Create(&model.BlogModel{Title: airticle.Title, Comment: airticle.Comment, Desc: airticle.Desc, UserId: int(tokenModel.UserId)})
	ctx.JSON(http.StatusOK, map[string]interface{}{
		"code": 200,
		"msg":  "ok",
		"data": airticle,
	})
}
func articlePut(ctx *gin.Context) {
	//获取数据库对象
	db := model.GetDB()
	defer db.Close()
	//获取数据库对象
	//var BlogModel model.BlogModel
	var airticle ModelArticle //表单绑定对象
	//参数验证
	err := ctx.ShouldBind(&airticle)
	if err != nil {
		ctx.JSON(http.StatusNotFound, map[string]interface{}{
			"code": 4001,
			"msg":  "数据绑定失败",
			"data": "",
		})
		return
	}
	//获取文章的id
	articleID := ctx.Param("article_id")
	// 更新数据库
	//更新数据库
	airticleInfo := map[string]interface{}{
		"title": airticle.Title,
		"comment": airticle.Comment,
		"desc":    airticle.Desc,
	}
	db.Model(&model.BlogModel{}).Where("id=?",articleID).Update(airticleInfo)
	ctx.JSON(http.StatusOK, map[string]interface{}{
		"code": 200,
		"msg":  "ok",
		"data": airticleInfo,
	})
}
func articleDelete(ctx *gin.Context) {
	//获取数据库对象
	db := model.GetDB()
	defer db.Close()
	//获取数据库对象
	var BlogModel model.BlogModel
	//获取文章的id
	articleID := ctx.Param("article_id")
	db.Model(&BlogModel).Where("id=?", articleID).Delete(&BlogModel)
	ctx.JSON(http.StatusOK, map[string]interface{}{
		"code": 200,
		"msg":  "ok",
		"data": "文章已删除",
	})
}
